﻿/**
 * GoText Palm: A program that allows to send text messages over the internet.
 *  Copyright (C) 2008 Nicola 'Gawaine' Racco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using GoTextPalm.Core;
using GoTextPalm.Core.Data;
using GoTextPalm.Core.Localization;
using GoTextPalm.Core.Persistence;

namespace GoTextPalm.Gui
{
    public partial class ConfigServiceForm : LocalizedForm
    {
        private Service s;
        private Logic logic;

        public ConfigServiceForm(Service s)
        {
            this.s = s;
            logic = new Logic();
            logic.SaveProcedureClosedEvent += new Logic.SaveProcedureClosedHandler(Logic_SaveProcedureClosed);
            logic.StatusChangedEvent += new Logic.StatusTextChangedHandler(Logic_StatusTextChanged);
            logic.ErrorCausedEvent += new Logic.ErrorCausedHandler(Logic_ErrorCausedEvent);
            InitializeComponent();
            header.Text = "Service Config";
            AddMenusToDictionary();
            UpdateResources();
        }

        protected override void AddMenusToDictionary()
        {
            AddMenuToDictionary(mnuSave, "mnuSave");
        }

        private void mnuSave_Click(object sender, EventArgs e)
        {
            if (s.NeedsUsername && txtUsername.Text.Trim().Length == 0)
                MessageBox.Show(Utility.Tr("ConfigServiceForm_needUser", 
                    "Username field is needed!"), header.Text, MessageBoxButtons.OK, 
                    MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            else if (s.NeedsPassword && txtPassword.Text.Trim().Length == 0)
                MessageBox.Show(Utility.Tr("ConfigServiceForm_needPass", "Password field is needed!"), header.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            logic.Username = txtUsername.Text.Trim();
            logic.Password = txtPassword.Text.Trim();
            logic.Nickname = txtNickname.Text.Trim();
            logic.Service = s;
            tabControl1.Enabled = mnuSave.Enabled = false;
            new Thread(new ThreadStart(logic.SaveProcedure)).Start();
        }

        private void ConfigServiceForm_Load(object sender, EventArgs e)
        {
            if (customInputPanel.SipSupported)
            {
                customInputPanel.Screen = screen;
                customInputPanel.Refresh();
            }
            txtName.Text = s.Name;
            txtUrl.Text = s.Url;
            if (s.Type == Service.ServiceType.PHONE)
                lblType.Text = Utility.Tr("ConfigServiceForm_lblType1", "Phone");
            else if (s.Type == Service.ServiceType.EMAIL)
                lblType.Text = Utility.Tr("ConfigServiceForm_lblType2", "Email");
            else
                lblType.Text = Utility.Tr("ConfigServiceForm_lblType3", "Phone and Email");
            String mm = null;
            if (s.MMMode == Service.MaxMessagesMode.DAILY)
                mm = Utility.Tr("ConfigServiceForm_lblMM1", "day");
            else
                mm = Utility.Tr("ConfigServiceForm_lblMM2", "month");
            lblMM.Text = String.Format(mm, s.MaxMessages);
            lblMC.Text = String.Format(Utility.Tr("ConfigServiceForm_lblMC", "mex"), s.MaxChars);
            pnlNickname.Visible = s.NeedsNickname;
            pnlUsername.Visible = s.NeedsUsername;
            pnlPassword.Visible = s.NeedsPassword;
            if (s.Config != null)
            {
                if (!s.Config.Nickname.IsNull)
                    txtNickname.Text = s.Config.Nickname.Value;
                if (!s.Config.Password.IsNull)
                    txtPassword.Text = s.Config.Password.Value;
                if (!s.Config.Username.IsNull)
                    txtUsername.Text = s.Config.Username.Value;
            }
        }


        public void Logic_StatusTextChanged(String text)
        {
            if (InvokeRequired)
            {
                Logic.StatusTextChangedHandler func = Logic_StatusTextChanged;
                Invoke(func, text);
                return;
            }
            if (!stsBar.Visible)
                stsBar.Visible = stsBar.ProgressStarted = true;
            stsBar.Text = text;
        }

        public void Logic_SaveProcedureClosed(bool aborted)
        {
            if (InvokeRequired)
            {
                Logic.SaveProcedureClosedHandler func = Logic_SaveProcedureClosed;
                Invoke(func, aborted);
                return;
            }
            stsBar.Visible = stsBar.ProgressStarted = false;
            tabControl1.Enabled = mnuSave.Enabled = true;
            if (!aborted)
            {
                DialogResult = DialogResult.OK;
                Close();
            }
        }

        public void Logic_ErrorCausedEvent(String text)
        {
            if (InvokeRequired)
            {
                Logic.ErrorCausedHandler func = Logic_ErrorCausedEvent;
                Invoke(func, text);
                return;
            }
            MessageBox.Show(text, header.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
        }

        private class Logic
        {
            public delegate void StatusTextChangedHandler(String text);
            public event StatusTextChangedHandler StatusChangedEvent;

            public delegate void SaveProcedureClosedHandler(bool aborted);
            public event SaveProcedureClosedHandler SaveProcedureClosedEvent;

            public delegate void ErrorCausedHandler(String text);
            public event ErrorCausedHandler ErrorCausedEvent;

            internal String Username, Password, Nickname;
            internal Service Service;

            public void SaveProcedure()
            {
                FireStatusTextChanged(Utility.Tr("ConfigServiceForm_stsSave1", "Saving Configuration ..."));
                try
                {
                    ServiceLogic.SaveServiceConfig(Service, Username, Nickname, Password);
                    FireStatusTextChanged(Utility.Tr("ConfigServiceForm_stsSave2", "Configuration Saved"));
                    FireSaveProcedureClosed(false);
                }
                catch (Exception e)
                {
                    FireErrorCaused(String.Format(
                        Utility.Tr("ConfigServiceForm_cantsaveconfig", 
                        "Cannot save configuration data: {0}"), e.Message));
                    FireSaveProcedureClosed(true);
                }
            }

            private void FireErrorCaused(String text)
            {
                if (ErrorCausedEvent != null)
                    ErrorCausedEvent(text);
            }

            private void FireStatusTextChanged(String text)
            {
                if (StatusChangedEvent != null)
                    StatusChangedEvent(text);
            }

            private void FireSaveProcedureClosed(bool aborted)
            {
                if (SaveProcedureClosedEvent != null)
                    SaveProcedureClosedEvent(aborted);
            }
        }
    }
}